package com.android.fragmentdemo.defineviews
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.android.fragmentdemo.R

class LooperListDataItemDecoration(context: Context) : RecyclerView.ItemDecoration() {

    private val dividerHeight = context.resources.getDimension(R.dimen.dp_1).toInt()
    private val topSpace = 0

    private var drawLastLine = true

    private val dividerPaint by lazy {
        Paint(Paint.ANTI_ALIAS_FLAG).apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.color_FDBB8FFF)
        }
    }

    private val rect by lazy {
        Rect()
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        //val childIndex = parent.getChildAdapterPosition(view)
        //outRect.right = dividerHeight
        val childIndex = parent.getChildAdapterPosition(view)
        //val itemCount = parent.adapter?.itemCount ?: 0
        val itemCount = parent.childCount
        if (childIndex != itemCount - 1) {
            outRect.right = dividerHeight
        } else {
            outRect.right = if (drawLastLine) {
                dividerHeight
            } else {
                0
            }
        }
    }

    override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(canvas, parent, state)
        //val itemCount = parent.adapter?.itemCount ?: 0
        val itemCount = parent.childCount
        val updateItemCount = if (drawLastLine) itemCount else itemCount - 1
        for (i in 0.until(updateItemCount)) {
            val child = parent.layoutManager?.getChildAt(i)
            val right = child?.right ?: 0
            Log.d(TAG, "right:${right}")
            val childHeight = child?.measuredHeight ?: 0
            Log.d(TAG, "childHeight:${childHeight}")
            if (childHeight > 0) {
                rect.set(right, topSpace, right + dividerHeight, childHeight)
                canvas.drawRect(rect, dividerPaint)
            }
        }
    }

    fun setDrawLastLine(drawLastLine: Boolean) {
        this.drawLastLine = drawLastLine
    }

    companion object {
        const val TAG = "LooperListDataItemDecoration"
    }
}